﻿using UnityEngine;
using System.Collections;

public class PrefabGenerator : MonoBehaviour {
	
	
	public GameObject[] createThis;  //List of possible prefabs
	
	private int rndNr; //This is for just a random number holder when we need it
	
	public int thisManyTimes = 3;
	public float overThisTime = 1.0f;
	
	public float xWidth;  //Define the square where prefabs will be generated
	public float yWidth;
	public float zWidth;
	
	public float xRotMax;  //Define maximum rotation of each prefab
	public float yRotMax = 180;
	public float zRotMax;
	
	public bool allUseSameRotation = false;
	private bool allRotationDecided = false;
	
	public bool detachToWorld = true;
	
	private float x_cur;  //These are used in the random palcement process
	private float y_cur;
	private float z_cur;
	
	private float xRotCur;  //These are used in the random protation process
	private float yRotCur;
	private float zRotCur;
	
	private float timeCounter;  //Counts the time :p
	private int effectCounter;  //You will guess ti
	
	private float trigger;  //Trigger: at which interwals should we generate a particle


	// Use this for initialization
	void Start () {
		trigger = overThisTime / thisManyTimes;  //Define the intervals of time of the prefab generation.
	}
	
	// Update is called once per frame
	void Update () {
		
		timeCounter += Time.deltaTime;
	
		if(timeCounter > trigger && effectCounter <= thisManyTimes)
			{
				rndNr = (int)Mathf.Floor(Random.value*createThis.Length);  //Decide which prefab to create
		
				x_cur = (float)(transform.position.x + (Random.value*xWidth) - (xWidth*0.5));  //Decide an actual place
				y_cur = (float)(transform.position.y + (Random.value*yWidth) - (yWidth*0.5));
				z_cur = (float)(transform.position.z + (Random.value*zWidth) - (zWidth*0.5));
		
				if(allUseSameRotation == false || allRotationDecided == false)  //Basically this plays only once if allRotationDecided=true, otherwise it plays all the time
				{
					xRotCur = (float)(transform.rotation.x + (float)(Random.value*xRotMax*2) - (xRotMax));  //Decide rotation
					yRotCur = (float)(transform.rotation.y + (float)(Random.value*yRotMax*2) - (yRotMax));  
					zRotCur = (float)(transform.rotation.z + (float)(Random.value*zRotMax*2) - (zRotMax));  
					allRotationDecided = true;
				}
		
				GameObject justCreated = (GameObject)Instantiate(createThis[rndNr], new Vector3(x_cur, y_cur, z_cur), transform.rotation);  //Create the prefab
				justCreated.transform.Rotate(xRotCur, yRotCur, zRotCur);
				
				if(detachToWorld == false)  //If needed we attach the freshly generated prefab to the object that is holding this script
				{
					justCreated.transform.parent = transform;
				}
			
				timeCounter -= trigger;  //Administration :p
				effectCounter += 1;
			}

	}
}
